<template>
  <n-space
    vertical
    size="large"
    style="height: 450px"
  >
    <n-layout-header bordered>
      <n-space justify="space-between">
        <n-gradient-text
          type="info"
          :size="24"
        >
          {{ editSettings.type === 1 ? "步骤性" : "习惯性" }}任务栏
        </n-gradient-text>
        <n-space>
          <template
            v-for="(data, index) in showCountTag"
            :key="index"
          >
            <n-tag type="success"> {{ data.name }}：{{ data.count }} </n-tag>
          </template>
        </n-space>
        <n-button
          @click="addNewOne()"
          :disabled="stageIsFinish"
          type="primary"
          dashed
          >添加任务</n-button
        >
      </n-space>
    </n-layout-header>
    <n-layout
      has-sider
      style="height: 370px"
    >
      <n-layout-sider
        bordered
        show-trigger
        collapse-mode="width"
        :collapsed-width="64"
        :width="150"
        :native-scrollbar="false"
        style="max-height: 320px"
      >
        <n-menu
          v-model:value="taskState"
          :collapsed-width="64"
          :collapsed-icon-size="22"
          :options="taskMenuOptions"
        />
      </n-layout-sider>
      <n-layout-content content-style="padding: 24px;">
        <n-data-table
          v-show="!showEmpty"
          :columns="columns"
          :data="tableData"
          :pagination="false"
          :bordered="false"
          :id="'taskDragTable' + editSettings.type"
          :max-height="270"
          :row-props="rowProps"
        />
        <n-data-table
          v-show="showEmpty"
          :columns="columns"
          :data="[]"
          :pagination="false"
          :bordered="false"
        />
      </n-layout-content>
    </n-layout>
    <n-dropdown
      :disabled="stageIsFinish"
      placement="bottom-start"
      trigger="manual"
      :x="xRef"
      :y="yRef"
      :options="options"
      :show="showDropdownRef"
      :on-clickoutside="onClickoutside"
      @select="handleSelect"
    />
    <TaskEditDrawer v-model="editSettings"></TaskEditDrawer>
    <TaskDelModal v-model="editSettings"></TaskDelModal>
    <TaskMoveModal v-model="moveTask"></TaskMoveModal>
  </n-space>
</template>
<script lang="ts" setup>
import TaskDelModal from "@/components/field/tasks/taskBtn/TaskDelModal.vue";
import TaskEditDrawer from "@/components/field/tasks/taskBtn/TaskEditDrawer.vue";
import TaskMoveModal from "@/components/field/tasks/taskBtn/TaskMoveModal.vue";
import { RemoveMethods } from "@/types/remove-methods";
import { FinishStage, FinishStageList } from "@model/StageFinish";
import { StateMoal } from "@model/StateMoal";
import { StageList, TaskIdsModal } from "@model/stage";
import { SurfaceSetting } from "@model/surfaceSetting";
import UseCacheFinishStageMap from "@pinias/UseCacheFinishStageMap";
import UseCacheIdStatMap from "@pinias/UseCacheIdStatMap";
import UseStage from "@pinias/UseStage";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import UseTask from "@pinias/UseTask";
import pinia from "@pinias/pinia";
import { renderIcon } from "@utils/CommonUtils";
import { timestampToDateTime } from "@utils/DateUtils";
import { Book } from "@vicons/ionicons5";
import {
  NButton,
  NDataTable,
  NSpace,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NLayoutHeader,
  NMenu,
  useMessage,
} from "naive-ui";
import Sortable from "sortablejs";
import { h, ref, onMounted, watch, reactive } from "vue";

// 全局数据
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting: SurfaceSetting = getSurfaceSetting();
const { getStageList } = UseStage(pinia);
const stageList: StageList = getStageList();
const { getTaskList } = UseTask(pinia);
const taskList = getTaskList();
const { getCacheFinishStageMap } = UseCacheFinishStageMap(pinia);
const cacheFinishStageMap = getCacheFinishStageMap();
const { getCacheIdStatMap } = UseCacheIdStatMap(pinia);
const cacheIdStatMap = getCacheIdStatMap();

// 当前页面数据
const showCountTag = ref(new Array<{ name: string; count: number }>());
const stageIsFinish = ref(false);
const props = defineProps(["type"]);
const showEmpty = ref(false);
const taskState = ref<string | undefined>(surfaceSetting.getTaskState(props.type));
const taskMenuOptions = ref(
  StateMoal.getStateMap().map(value => {
    value.icon = renderIcon(Book);
    return value;
  }),
);
const editSettings = reactive<{
  toEdit: boolean;
  toDelete: boolean;
  toDealRowId: number | undefined;
  type: number;
  stageId: number;
}>({
  toEdit: false,
  toDelete: false,
  toDealRowId: undefined,
  type: props.type,
  stageId: 0,
});
const moveTask = reactive<{
  toMove: boolean;
  taskId: number;
  type: number;
  state: string;
  originalStageId: number;
  toSaveStageId: number | null;
  toSaveField: number | undefined;
}>({ toMove: false, taskId: 0, type: 0, state: "", originalStageId: 0, toSaveStageId: 0, toSaveField: 0 });
class RowData {
  id: number;
  name: string;
  desc: string;
  deadLine: string;
  mentionTime: string;
  takeTime: string | number;
  finishTime: number;
  failTime: number;
  constructor(data: RemoveMethods<RowData>) {
    Object.assign(this, data);
  }
  static getNullModel() {
    return new RowData({
      id: -1,
      name: "",
      desc: "",
      mentionTime: "",
      deadLine: "",
      takeTime: "",
      finishTime: 0,
      failTime: 0,
    });
  }
}

// 表格数据
const getTableData = async () => {
  const result = [];
  const showStage = surfaceSetting.getShowStage();
  const satgeData = stageList.getStageDataById(showStage);
  if (satgeData !== undefined) {
    stageIsFinish.value = satgeData.finished;
    if (satgeData.finished) {
      const fieldId = satgeData.fatherId;
      const finishStageList = await cacheFinishStageMap.getFinishStageList(fieldId);
      const finishStage = FinishStageList.getFinishStage(finishStageList, satgeData.id);
      if (finishStage !== undefined && taskState.value === "finished") {
        const taskDatas = FinishStage.getTaskDataList(finishStage, props.type);
        showCountTag.value = [{ name: "已结束", count: taskDatas.length }];
        for (let i = 0; i < taskDatas.length; i++) {
          const oldDdata = taskDatas[i];
          result.push(
            new RowData({
              id: oldDdata.id,
              name: oldDdata.name,
              desc: oldDdata.desc,
              deadLine: timestampToDateTime(oldDdata.timeMentionModal.deadLine),
              mentionTime: timestampToDateTime(oldDdata.mentionTime),
              takeTime: await cacheIdStatMap.getTakeTime(oldDdata.id, []),
              finishTime: oldDdata.finishTime,
              failTime: oldDdata.failTime,
            }),
          );
        }
      }
    } else {
      // 未结束阶段
      const stateMoal = TaskIdsModal.getStateModal4Task(satgeData?.task, props.type);
      showCountTag.value = StateMoal.getStateCount(stateMoal);
      if (stateMoal !== undefined) {
        const list = StateMoal.getStateId(stateMoal, taskState.value);
        //console.log(taskState,showStage,satgeData,stateMoal,list)
        for (let i = 0; i < list.length; i++) {
          const id = list[i];
          const oldDdata = taskList.getTaskDataById(id);
          if (oldDdata !== undefined) {
            // console.log((task["1"]["已完成"].length+task["2"]["已完成"].length))
            result.push(
              new RowData({
                id: oldDdata.id,
                name: oldDdata.name,
                desc: oldDdata.desc,
                deadLine: timestampToDateTime(oldDdata.timeMentionModal.deadLine),
                mentionTime: timestampToDateTime(oldDdata.mentionTime),
                takeTime: await cacheIdStatMap.getTakeTime(oldDdata.id, []),
                finishTime: oldDdata.finishTime,
                failTime: oldDdata.failTime,
              }),
            );
          }
        }
      }
    }
  }
  if (result.length == 0) {
    result.push(RowData.getNullModel());
    showEmpty.value = true;
  } else showEmpty.value = false;
  return result;
};
const tableData = ref(new Array<RowData>());
const watchTableData = async () => {
  // editSettings.state = taskState.value;
  tableData.value = await getTableData();
};
watch(() => {
  if (taskState.value !== undefined) surfaceSetting.setTaskState(editSettings.type, taskState.value);
  return taskState.value;
}, watchTableData);
watch(surfaceSetting.showStage, watchTableData);
// 渲染表头
const play = (row: RowData) => {
  // message.info(`Play ${row.title}`);
  console.log(row);
};
const createColumns = () => {
  return [
    // {
    //   title: "id",
    //   key: "id",
    //   width: 100,
    // },
    {
      title: "名字",
      key: "name",
    },
    {
      title: "描述",
      key: "desc",
      width: 100,
      ellipsis: {
        tooltip: true,
      },
    },
    {
      title: "截止时间",
      key: "deadLine",
    },
    {
      title: "提醒时间",
      key: "mentionTime",
    },
    {
      title: "所花时间",
      key: "takeTime",
    },
    {
      title: "打卡次数",
      key: "finishTime",
    },
    {
      title: "失败次数",
      key: "failTime",
    },
    {
      title: "Action",
      key: "actions",
      render(row: RowData) {
        return h(
          NButton,
          {
            strong: true,
            tertiary: true,
            size: "small",
            id: "handle-drag",
            onClick: () => play(row),
          },
          { default: () => "上下移动" },
        );
      },
    },
  ];
};
const columns = createColumns();

// 右键菜单
const rowProps = (row: RowData) => {
  return {
    onContextmenu: (e: MouseEvent) => {
      // message.info(JSON.stringify(row, null, 2));
      showDropdownRef.value = true;
      xRef.value = e.clientX;
      yRef.value = e.clientY;
      // console.log('rowProps',row)
      editSettings.toDealRowId = row.id;
    },
  };
};
const options = [
  {
    label: "编辑",
    key: "edit",
  },
  {
    label: "移动",
    key: "move",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "删除"),
    key: "delete",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "完成"),
    key: "finish",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "失败"),
    key: "fail",
  },
];
const showDropdownRef = ref(false);
const xRef = ref(0);
const yRef = ref(0);
const onClickoutside = () => {
  showDropdownRef.value = false;
};
const handleSelect = (key: string, node: string) => {
  console.log(key, node);
  showDropdownRef.value = false;
  if (key == "edit") {
    editSettings.toEdit = true;
    editSettings.stageId = surfaceSetting.getShowStage();
  }
  if (key == "delete") {
    editSettings.toDelete = true;
  }
  if (key == "move") {
    // editSettings.toDelete = true;
    if (editSettings.toDealRowId !== undefined) {
      moveTask.type = props.type;
      moveTask.originalStageId = surfaceSetting.getShowStage();
      moveTask.toSaveStageId = moveTask.originalStageId;
      moveTask.state = taskState.value !== undefined ? taskState.value : "";
      moveTask.taskId = editSettings.toDealRowId;
      moveTask.toMove = true;
    }
  }
  if (key == "finish" || key === "fail") {
    if (
      taskState.value !== undefined &&
      taskState.value !== "finished" &&
      taskState.value !== "stopping" &&
      editSettings.toDealRowId !== undefined
    ) {
      taskList.finishTask(editSettings.toDealRowId, props.type, taskState.value, stageList, surfaceSetting, key);
      surfaceSetting.TaskListKey = new Date().getTime();
      surfaceSetting.taskBoardList.key = new Date().getTime() + 10;
    } else message.error("已结束和未开始的不可完成或失败");
  }
};
const message = useMessage();
const addNewOne = () => {
  // console.log(editSettings);
  editSettings.stageId = surfaceSetting.getShowStage();
  editSettings.toDealRowId = undefined;
  editSettings.toEdit = true;
};

// 拖拽逻辑
function setSort() {
  const str = "#taskDragTable" + editSettings.type + " table tbody";
  const el = document.querySelector(str);
  new Sortable(el, {
    handle: "#handle-drag",
    sort: true,
    ghostClass: "sortable-ghost",
    onEnd: (e: any) => {
      const showStage = surfaceSetting.getShowStage();
      const satgeData = stageList.getStageDataById(showStage);
      if (satgeData !== undefined && !stageIsFinish.value) {
        const stateMoal = TaskIdsModal.getStateModal4Task(satgeData?.task, props.type);
        if (stateMoal !== undefined) {
          const list = StateMoal.getStateId(stateMoal, taskState.value);
          const targetRow = list.splice(e.oldIndex, 1)[0];
          list.splice(e.newIndex, 0, targetRow);
        }
      }
      // console.log(tableData)
      surfaceSetting.StageListKey = new Date().getTime();
    },
  });
}
onMounted(async () => {
  await watchTableData();
  setSort();
});
</script>
